package com.test.demo.main.activity.dynamic

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.test.demo.R
import com.test.demo.base.BaseActivity
import com.test.demo.databinding.ActivityDynamicDetailBinding
import com.test.demo.ext.loadUrl
import com.test.demo.ext.setImageUrl
import com.test.demo.main.adapter.TopicChildAdapter
import com.test.demo.main.bean.MediumBean
import com.test.demo.main.dialog.ShareDynamicDialog
import com.test.demo.utils.VideoPlayActivity
import com.test.demo.utils.ViewPager2Activity
import com.test.demo.utils.data.ConstUtils
import com.test.demo.utils.glide.widget.SimpleDraweeView
import com.test.demo.main.fragment.CommentFragment
import com.test.demo.main.fragment.LikeFragment
import com.test.demo.main.fragment.RepostFragment
import com.test.demo.widget.GridItemDecoration
import net.lucode.hackware.magicindicator.buildins.UIUtil

/** 动态详情页 */
class DynamicDetailActivity : BaseActivity<DynamicDetailViewModel, ActivityDynamicDetailBinding>() {

    private var mediaList = ArrayList<MediumBean>();

    var repostFragment = RepostFragment()
    var commentFragment = CommentFragment()
    var likeFragment = LikeFragment()

    private var currentFragment: Fragment? = null

    val times = 1000

    var time: Long = 0L

    companion object {
        fun getInstance(context: Context, list: ArrayList<MediumBean>) {
            var intent = Intent(context, DynamicDetailActivity::class.java)
            val bundle = Bundle()
            bundle.putSerializable("material", list)
            intent.putExtras(bundle)
            context.startActivity(intent)
        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_dynamic_detail
    }

    override fun initView(savedInstanceState: Bundle?) {
        initFragment()
        switchFragment(commentFragment)

        binding.headerTitle.toolbarUsername.text = "#热爱和平的人儿#"
        var bundle = intent.extras
        mediaList = bundle!!.get("material") as ArrayList<MediumBean>
        if (mediaList.size == 0) {
            binding.imageLayout.visibility = View.GONE
        }
        initImageList(mediaList)
    }

    /**
     * fragment初始化
     */
    private fun initFragment() {
        likeFragment = LikeFragment()
        repostFragment = RepostFragment()
        commentFragment = CommentFragment()

        commentFragment.setOnItemListener(object : CommentFragment.OnItemListener {
            override fun onItemClick() {
                openInputManager()
            }
        })

    }

    override fun initListener() {
        super.initListener()

        binding.headerTitle.toolbarBack.setOnClickListener { finish() }

        binding.bottomBar.tvRepost.setOnClickListener {
            binding.bottomBar.let {
                it.tvRepost.setTextColor(resources.getColor(R.color.detail_highlight_text))
                it.repostIndicator.visibility = View.VISIBLE

                it.tvLike.setTextColor(resources.getColor(R.color.detail_normal_text))
                it.likeIndicator.visibility = View.INVISIBLE

                it.tvCommentContent.setTextColor(resources.getColor(R.color.detail_normal_text))
                it.commentIndicator.visibility = View.INVISIBLE
            }
            switchFragment(repostFragment)
        }

        binding.bottomBar.tvCommentContent.setOnClickListener {
            binding.bottomBar.let {
                it.tvRepost.setTextColor(resources.getColor(R.color.detail_normal_text))
                it.repostIndicator.visibility = View.INVISIBLE

                it.tvLike.setTextColor(resources.getColor(R.color.detail_normal_text))
                it.likeIndicator.visibility = View.INVISIBLE

                it.tvCommentContent.setTextColor(resources.getColor(R.color.detail_highlight_text))
                it.commentIndicator.visibility = View.VISIBLE
            }
            switchFragment(commentFragment)
        }

        binding.bottomBar.tvLike.setOnClickListener {
            binding.bottomBar.let {
                it.tvRepost.setTextColor(resources.getColor(R.color.detail_normal_text))
                it.repostIndicator.visibility = View.INVISIBLE

                it.tvLike.setTextColor(resources.getColor(R.color.detail_highlight_text))
                it.likeIndicator.visibility = View.VISIBLE

                it.tvCommentContent.setTextColor(resources.getColor(R.color.detail_normal_text))
                it.commentIndicator.visibility = View.INVISIBLE
            }
            switchFragment(likeFragment)
        }

        //分享
        binding.headerTitle.toolbarMore.setOnClickListener {
            var shareDialog = ShareDynamicDialog()
            shareDialog.show(supportFragmentManager, "test")
        }

        binding.llOperate.bottombarRetweet.setOnClickListener {
            var shareDialog = ShareDynamicDialog()
            shareDialog.show(supportFragmentManager, "test")
        }

        binding.llOperate.editComment.setHorizontallyScrolling(false)
        // 输入框监听
        binding.llOperate.editComment.setOnEditorActionListener(object :
            TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, ketEvent: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED ||
                    actionId == EditorInfo.IME_ACTION_SEND ||
                    (ketEvent != null && ketEvent.keyCode == KeyEvent.KEYCODE_ENTER)
                ) {
                    binding.llOperate.editComment.text.clear()
                    closeInputManager()
                    return true
                }
                return false
            }

        })

        binding.llOperate.editComment.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val editText = binding.llOperate.editComment
                val lineCount = editText.lineCount
                val lineHeight = editText.lineHeight

                val maxLines = 5
                val newHeight =
                    (lineHeight * lineCount + editText.paddingTop + editText.paddingBottom)

                // 确保最大高度不超过5行
                if (lineCount <= maxLines) {
                    binding.llOperate.editComment.height = newHeight
                    editText.requestLayout()
                }
            }
        })
    }

    private fun initImageList(urlList: List<MediumBean>?) {
        if (urlList?.size == 1) {
            if (urlList[0].type == 1) {
                setGoneLayout(1)
                binding.ivBigImage.setImageResource(urlList[0].resId!!)
//                binding.ivBigImage.post {
//                    if (binding.ivBigImage.width > binding.ivBigImage.height) {
//                        setImageViewDimensions(binding.ivBigImage, binding.ivBigImage.width, binding.ivBigImage.height)
//                    } else {
//                        setVerticalView(binding.ivBigImage, binding.ivBigImage.width, binding.ivBigImage.height, urlList[0].url)
//                    }
//                }
                binding.ivBigImage.setOnClickListener {
                    ViewPager2Activity.startNetUrl(this@DynamicDetailActivity, urlList, 0)
                }
            } else {
                setGoneLayout(3)
                binding.remotePlaybackWndSv.let {
                    it.setUp(urlList[0].url, "")
                    val shopMasterPicture =
                        urlList[0].url + "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto"
                    it.posterImageView?.setImageUrl("${shopMasterPicture}")
                    it.posterImageView?.setOnClickListener {
                        setVideoPlay(urlList[0].url)
                    }
                    it.textureViewContainer?.setOnClickListener {
                        setVideoPlay(urlList[0].url)
                    }
                }
            }
        } else {
            setGoneLayout(2)
            var topicChildAdapter = TopicChildAdapter()
            topicChildAdapter.setList(urlList)
            val divider: GridItemDecoration = GridItemDecoration.Builder(this)
                .setHorizontalSpan(resources.getDimension(com.example.common_library.R.dimen.dp_5))
                .setVerticalSpan(resources.getDimension(com.example.common_library.R.dimen.dp_5))
                .setColorResource(R.color.white)
                .setShowLastLine(true)
                .build()

            binding.twoRecycler.addItemDecoration(divider)
            binding.twoRecycler.layoutManager = GridLayoutManager(this, 3)
            binding.twoRecycler.adapter = topicChildAdapter
            topicChildAdapter.setOnItemClickListener(object : OnItemClickListener {
                override fun onItemClick(
                    adapter: BaseQuickAdapter<*, *>,
                    view: View,
                    position: Int
                ) {
                    ViewPager2Activity.startNetUrl(this@DynamicDetailActivity, urlList, position)
                }
            })
        }
    }

    private fun setGoneLayout(showType: Int) {
        when (showType) {
            1 -> {
                binding.ivBigImage.visibility = View.VISIBLE
                binding.twoRecycler.visibility = View.GONE
                binding.cardView.visibility = View.GONE
            }
            2 -> {
                binding.ivBigImage.visibility = View.GONE
                binding.twoRecycler.visibility = View.VISIBLE
                binding.cardView.visibility = View.GONE
            }
            3 -> {
                binding.ivBigImage.visibility = View.GONE
                binding.twoRecycler.visibility = View.GONE
                binding.cardView.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 设置竖向大图片
     */
    private fun setVerticalView(bigImage: SimpleDraweeView, width: Int, height: Int, url: String?) {
        bigImage.layoutParams.width = UIUtil.dip2px(this, 150.0)
        bigImage.layoutParams.height = UIUtil.dip2px(this, 300.0)
        bigImage.scaleType = ImageView.ScaleType.CENTER_CROP
        bigImage.layoutParams = bigImage.layoutParams
        bigImage.loadUrl(url)
    }

    /**
     * 判断图片尺寸是横向还是竖向
     */
    private fun getHorizontalvertical(width: Int, height: Int): Boolean {
        return (width > height)
    }

    fun getImageAspectRatio(width: Int, height: Int): Float {
        return width.toFloat() / height.toFloat()
    }

    fun setImageViewDimensions(imageView: ImageView, width: Int, height: Int) {
        // 计算图片的宽高比
        imageView.layoutParams.width =
            UIUtil.getScreenWidth(this) - (2 * UIUtil.dip2px(this, 16.0))
        imageView.layoutParams.height = height
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        // 更新视图
        imageView.layoutParams = imageView.layoutParams
    }

    override fun createObserver() {
        super.createObserver()
        //接口回调处理
    }

    /**
     * 切换fragment
     */
    private fun switchFragment(fragment: Fragment) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()

        // 如果当前 Fragment 不为空，移除它
        currentFragment?.let {
            fragmentTransaction.remove(it)
        }

        // 添加新 Fragment
        fragmentTransaction.replace(R.id.ll_container, fragment)
        fragmentTransaction.commitAllowingStateLoss()

        // 更新当前 Fragment
        currentFragment = fragment
    }

    /**
     * 播放视频操作
     */
    private fun setVideoPlay(url: String?) {
        var bundle = Intent()
        bundle.setClass(this@DynamicDetailActivity, VideoPlayActivity::class.java)
        bundle.putExtra(ConstUtils.VIDEO_PLAY_URL, url)
        startActivity(bundle)
    }

    fun setClick(): Boolean {
        var boolean = false
        val tempTime = System.currentTimeMillis()
        if ((tempTime - time) > times) {
            time = tempTime
            boolean = true
        } else {
            time = tempTime
            boolean = false
        }
        return boolean
    }

    /**
     * 软键盘收起
     */
    fun closeInputManager() {
        //收起软键盘
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(binding.llOperate.editComment.windowToken, 0)
    }

    /**
     * 软键盘弹起
     */
    fun openInputManager() {
        //编辑视图获取焦点
        binding.llOperate.editComment.requestFocus()
        //展开软键盘
        val imm: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
    }

}